<style lang="less">
    @import "../../../../styles/common.less";
</style>

<template>
    <div @click="closeLayer" class="peak-wapper">
        <Row :gutter="10">
            <Col span="17">
                <Card dis-hover :bordered="false">
                    <p slot="title">
                        表单数据
                    </p>
                    <Card dis-hover :bordered="false" :padding="0" class="form-card">
                        <Form ref="formDataView" :model="formData" :rules="formDataRule"  label-position="top">
                            <Row>
                                <Col span="8">
                                    <FormItem label="用户名" prop="loginName" class="form-item">
                                        <Input type="text" v-model="formData.loginName" placeholder="请输入您的用户名" :disabled="read==1?true:false"></Input>
                                    </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="所属部门" :required="true" class="form-item">
                                    <!--封装文本树形结构-->
                                    <div class="input-tree">
                                        <div class="ivu-input" :class="selectDeptTip?'redline':''" placeholder="请输入所属部门"  @click="selectDept">{{selectDeptTxt}}</div>
                                        <div class="ivu-form-item-error-tip" v-if="selectDeptTip && (read==1?false:true)">所属部门不能为空</div>
                                        <div class="tree-wapper" v-show="DeptTree && (read==1?false:true)" @click="stopDefault">
                                            <Tree ref="DeptTree" :data="deptData" @on-check-change="selectChangeDept" show-checkbox multiple></Tree>
                                        </div>
                                    </div>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                    <FormItem label="所属角色" :required="true" class="form-item">
                                        <!--封装文本树形结构-->
                                        <div class="input-tree">
                                            <div class="ivu-input" :class="selectRoleTip?'redline':''"  placeholder="请输入文字"  @click="selectRole">{{selectRoleTxt}}</div>
                                            <div class="ivu-form-item-error-tip" v-if="selectRoleTip && (read==1?false:true)">所属角色不能为空</div>
                                            <div class="tree-wapper" v-show="roleTree && (read==1?false:true)" @click="stopDefault">
                                                <Tree ref="roleTree" :data="roleData" @on-check-change="selectChangeRole" show-checkbox multiple></Tree>
                                            </div>
                                        </div>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span="8">
                                <FormItem label="姓名" prop="name" class="form-item">
                                    <Input type="text" v-model="formData.name" placeholder="请输入您的真实姓名" :disabled="read==1?true:false"></Input>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="邮箱" prop="email" class="form-item">
                                    <Input type="text" v-model="formData.email" placeholder="请输入您的邮箱" :disabled="read==1?true:false"></Input>
                                </FormItem>
                                </Col>
                                <Col span="8">
                                <FormItem label="手机号" prop="mobile" class="form-item">
                                    <Input type="text" v-model="formData.mobile" placeholder="请输入您的手机号" :disabled="read==1?true:false"></Input>
                                </FormItem>
                                </Col>
                            </Row>
                            <Row v-if="!Boolean(id)">
                                <Col span="8">
                                    <FormItem label="密码" prop="password" class="form-item">
                                        <Input type="password" v-model="formData.password" placeholder="请输入您的密码"></Input>
                                    </FormItem>
                                </Col>
                                <Col span="8">
                                    <FormItem label="确认密码" prop="rePassword" class="form-item">
                                        <Input type="password" v-model="rePassword" placeholder="请再次输入你的密码"></Input>
                                    </FormItem>
                                </Col>
                                <Col span="8"></Col>
                            </Row>
                        </Form>
                    </Card>
                </Card>
            </Col>
            <Col span="7" v-if="read!=1">
                <Card dis-hover :bordered="false">
                    <p slot="title">
                        数据操作
                    </p>
                    <div style="text-align: right" v-if="!Boolean(id)">
                        <Button type="primary" @click="handleSaveRole('formDataView')">保存</Button>
                        <Button type="ghost" @click="handleReset('formDataView')">重置</Button>
                    </div>
                    <div style="text-align: right" v-else>
                        <Button type="primary" @click="handleUpdateRole('formDataView')">修改</Button>
                        <Button type="ghost" @click="handleBackHome('formDataView')">返回</Button>
                    </div>
                </Card>
            </Col>
        </Row>

    </div>
</template>

<script>
  import { fetchGetData,fetchPostData,adminUrl} from '@/libs/fetch.js'
  import util from '@/libs/util.js'
  export default {
    name: 'addUser',
    data () {
      const mobileValidator=(rule,value,callback)=>{
        if(value===''){
          callback(new Error('手机号不能为空'));
        }else if(!/^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/.test(value)){
          callback(new Error('手机号格式不正确'));
        }else{
          callback();
        }
      };
      const repasswordValidator=(rule,value,callback)=>{
        if(this.rePassword===''){
          callback(new Error('确认密码不能为空'));
        }else if(this.rePassword!=this.formData.password){
          callback(new Error('二次输入的密码不一致'));
        }else {
          callback();
        }
      }
      return {
        id:this.$route.query.id,
        read:this.$route.query.read,
        rePassword:'',
        //模拟下拉树begin
        roleTree:false,
        selectRoleTip:false,
        selectRoleTxt:'',
        DeptTree:false,
        selectDeptTip:false,
        selectDeptTxt:'',
        selectNum:[false,false],
        //模拟下拉树end
        formData:{
          loginName:'',
          deptIds:[],
          roleIds:[],
          name:'',
          email:'',
          mobile:'',
          password:''
        },
        formDataRule:{
          loginName: [
            { required: true, message: '用户名不能为空', trigger: 'blur'}
          ],
          name: [
            { required: true, message: '姓名不能为空', trigger: 'blur'}
          ],
          email:[
            { required: true, message: '邮箱不能为空', trigger: 'blur'},
            { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
          ],
          mobile: [
            {required: true, validator:mobileValidator, trigger: 'blur'}
          ],
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur'},
            { type: 'string', min: 6, message: '密码长度最少为6位', trigger: 'blur' }
          ],
          rePassword:[
            { required: true,validator:repasswordValidator, trigger: 'blur'}
          ]
        },
        roleData:[],
        deptData:[]
      };
    },
    methods: {
      //模拟下拉树begin
      closeLayer(){
        if(this.roleTree){
          this.roleTree=false;
        }
        if(this.DeptTree){
          this.DeptTree=false;
        }
        if(this.selectNum[1]){
          if(this.selectRoleTxt==''){
            this.selectRoleTip=true;
          }else{
            this.selectRoleTip=false;
          }
        }
        if(this.selectNum[0]){
          if(this.selectDeptTxt==''){
            this.selectDeptTip=true;
          }else{
            this.selectDeptTip=false;
          }
        }
      },
      initSelect(){
        this.roleTree=false;
        this.DeptTree=false;
        this.selectNum=[false,false];
      },
      selectRole(event){//选择角色
        event.preventDefault();
        event.stopPropagation();
        this.initSelect();
        this.roleTree=true;
        this.selectNum[1]=true;
      },
      selectDept(event){//选择部门
        event.preventDefault();
        event.stopPropagation();
        this.initSelect();
        this.DeptTree=true;
        this.selectNum[0]=true;
      },
      stopDefault(event){//点击遮罩 阻止事件传播
        event.preventDefault();
        event.stopPropagation();
        return false;
      },

      //模拟下拉树end
      selectChangeRole(){
        let res=util.mapTree(this.$refs.roleTree.getCheckedNodes());
        this.selectRoleTxt=res.resvalue;
        this.formData.roleIds=res.reskey;
      },
      selectChangeDept(){
        let res=util.mapTreeChild(this.$refs.DeptTree.getCheckedNodes());
        this.selectDeptTxt=res.resvalue;
        this.formData.deptIds=res.reskey;
      },
      handleSaveRole(name){
        if(this.selectRoleTxt==''){
          this.selectRoleTip=true;
        }
        if(this.selectDeptTxt==''){
          this.selectDeptTip=true;
        }
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.selfValid()){
              fetchPostData(adminUrl+'/admin/user/addUser',this.formData)
                .then(data=>{
                  if(data.status==1){
                    let _that=this;
                    this.$Notice.success({
                      title: data.message,
                      duration:2,
                      onClose:function () {
                        util.closeCurrentTag(_that,_that.$route.name,'user');
                      }
                    })
                  }else{
                    this.$Notice.error({
                      title: '保存失败',
                      desc: data.message,
                      duration:0
                    });
                  }
                })
            }
          } else {
            this.$Message.error('信息输入有误!');
          }
        })
      },
      handleReset(name){
        this.selectRoleTxt='';
        this.selectRoleTip=false;
        this.selectDeptTxt='';
        this.selectDeptTip=false;
        this.$refs[name].resetFields();
      },
      handleUpdateRole(name){
        if(this.selectRoleTxt==''){
          this.selectRoleTip=true;
        }
        if(this.selectDeptTxt==''){
          this.selectDeptTip=true;
        }
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.selfValid()){
              fetchPostData(adminUrl+'/admin/user/update',this.formData)
                .then(data=>{
                  if(data.status==1){
                    let _that=this;
                    this.$Notice.success({
                      title: data.message,
                      duration:2,
                      onClose:function () {
                        util.closeCurrentTag(_that,_that.$route.name,'user');
                      }
                    })
                  }else{
                    this.$Notice.error({
                      title: '修改失败',
                      desc: data.message,
                      duration:0
                    });
                  }
                })
            }
          } else {
            this.$Message.error('信息输入有误!');
          }
        })
      },
      handleBackHome(){
        util.closeCurrentTag(this,this.$route.name,'user');
      },
      selfValid(){
        if(this.selectRoleTxt==''){
          this.selectRoleTip=true;
          return false;
        }
        if(this.selectDeptTxt==''){
          this.selectDeptTip=true;
          return false;
        }
        return true;
      }
    },
    created(){
      util.setNavTitle(this,util.getComTitle(this.id,this.read,'用户'));
      if(this.id){
          fetchGetData(adminUrl+'/admin/user/detail/'+this.id,{}).then(data=>{
            if(data.status==1){
                this.formData=data.data;
            }else{
              this.$Message.error(data.message);
            }
          });
      }
      fetchGetData(adminUrl+'/admin/role/query',{userId:this.id}).then(data=>{
        if(data.status==1){
          this.roleData=data.data;
          if(this.id){
           let res=util.mapTree(this.roleData);
           this.selectRoleTxt=res.resvalue;
          }
        }else{
          this.$Message.error(data.message);
        }
      });
      fetchGetData(adminUrl+'/admin/dept/query',{userId:this.id}).then(data=>{
        if(data.status==1){
          this.deptData=data.data;
          if(this.id){
            let res=util.mapTreeTxt(this.deptData);
            this.selectDeptTxt=res.resvalue;
          }
        }else{
          this.$Message.error(data.message);
        }
      });
    }
  };
</script>